package zj.xinxin.business.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import zj.xinxin.api.moudle.system.api.LoginLogService;
import zj.xinxin.common.constant.SystemConst;
import zj.xinxin.common.result.ResponseResult;
import zj.xinxin.common.utils.JwtTokenUtil;
import zj.xinxin.api.moudle.utils.ConsumerUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录成功的 处理器
 * @author junzhou
 * @date 2022/3/23 14:37
 * @since 1.8
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        loginLogService.saveLoginLog(httpServletRequest, true);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter()
                .write(JSON.toJSONString(
                        ResponseResult.success(
                                SystemConst.LOGIN_SUCCESS,
                                "Bearer " + jwtTokenUtil.generatorToken(
                                        ConsumerUtil.getUserDetails()))));
    }
}
